package com.ruoyi.goods.GoodsStore.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.goods.GoodsStore.domain.*;
import com.ruoyi.goods.GoodsStore.mapper.GoodsMapper;

import com.ruoyi.goods.GoodsStore.service.*;
import com.ruoyi.goods.GoodsStore.vo.GoodsStoreVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 物品信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-27
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

 @Autowired
 private IGoodsStoreService goodsStoreService;
 @Autowired
 private IStoreService storeService;
 @Autowired
 private IStockBillService stockBillService;
 @Autowired
 private IGoodsCategoryService categoryService;

    /**
     * 查询物品信息列表
     *
     * @param goodsStoreVo 物品信息
     * @return 物品信息
     */
    @Override
    public List<GoodsStoreVo> selectGoodsList(GoodsStoreVo goodsStoreVo) {
        if(goodsStoreVo.getCategoryId()!=null){
            List<Long> allChildren = categoryService.AllChildren(goodsStoreVo.getCategoryId());
            goodsStoreVo.setCategoryIds(allChildren);
        }
        List<GoodsStoreVo> goodsList = getBaseMapper().selectGoodsList(goodsStoreVo);
        for (GoodsStoreVo storeVo : goodsList) {
            GoodsCategory category = categoryService.getById(storeVo.getCategoryId());
            storeVo.setCategoryName(category.getCategoryName());
        }
        return goodsList;
    }

    //明细列表
    @Override
    public List<GoodsStoreVo> selectDetailedList(Long goodsId) {
       List<GoodsStoreVo> list=getBaseMapper().selectDetailedList(goodsId);
        for (GoodsStoreVo goodsStoreVo : list) {
            StockBill stockBill = stockBillService.getById(goodsStoreVo.getBillId());
            Store store = storeService.getById(stockBill.getStoreId());
            goodsStoreVo.setStoreName(store.getStoreName());
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteByIds(Long id) {
        GoodsStore goodsStore = goodsStoreService.selectGoodsStoreById(id);
        if (goodsStore==null) {
            return super.removeById(id);
        }
        boolean delete=goodsStoreService.deleteGoodsStore(id);
        if (!delete) {
            throw new ServiceException("中间表删除失败");
        }
        return super.removeById(id);

    }
}
